<template>
	<view v-else class="goods-detail" :class="themeName">
		<!-- 轮播图 -->
		<goods-swiper :images="goodsInfo.goods_image" :video="goodsInfo.video" :video-cover="goodsInfo.video_cover" />

		<!-- 商品基础信息 -->
		<view class="goods-info">
			<view class="flex row-between">
				<price :content="goodsInfo.sell_price" main-size="46rpx" minor-size="32rpx" :color="themeColor">
					<view slot="suffix" class="muted line-through m-l-12 xxs">
						<price :content="goodsInfo.lineation_price" prefix="原价￥" :line-through="true" />
					</view>
				</price>
				<view class="sm lighter share" @tap="showShare=true">
					<u-icon name="share" />
					<text class="m-l-10">分享</text>
				</view>
			</view>
			<view class="goods-name lg">{{ goodsInfo.name }}</view>
			<view class="flex row-between muted xs">
				<template v-if="goodsInfo.stock_show">
					<view>库存: {{ goodsInfo.total_stock }}</view>
				</template>
				<view>销量: {{ goodsInfo.sales_num }}</view>
				<view>浏览量: {{ goodsInfo.click_num }}</view>
			</view>
		</view>


		<!-- S 优惠 -->
		<view class="nr discounts">
			<text class="muted">优惠</text>
			<view class="xxs m-l-20 flex-1">
				<view class="flex" @tap="showCoupons = true">
					<u-tag text="领券" mode="plain" size="mini" class="m-r-20" :color="themeColor"
						:border-color="themeColor" />
					<block v-for="item in goodsCouponSpecs" :key="item">
						<view class="coupon-tag">{{ item }}</view>
					</block>
					<u-icon name="arrow-right" class="muted nr" style="margin-left: auto;" />
				</view>

				<!-- 				<view class="flex m-t-30">
					<u-tag
					  text="积分" 
					  mode="plain" 
					  size="mini" 
					  class="m-r-20"
					  :color="themeColor"
					  :border-color="themeColor" 
					/>
					<text class="nr">订单完成可获得{{ 0 }}积分</text>
				</view> -->
			</view>
		</view>
		<!-- Coupons Popup -->
		<u-popup v-model="showCoupons" mode="bottom" border-radius="14" :closeable="false"
			:safe-area-inset-bottom="true">
			<view class="coupons">
				<view class="coupons-header">
					<text>领券</text>
					<u-icon name="close" color="#666666" @tap="showCoupons = false" />
				</view>

				<view class="coupons-main">
<!-- 					<view class="flex m-b-30">
										<u-tag
						  text="积分" 
						  mode="plain" 
						  size="mini" 
						  class="m-r-20"
						  :color="themeColor"
						  :border-color="themeColor" 
						/>
						<text class="nr">订单完成可获得{{ 0 }}积分</text>
					</view> -->
					<scroll-view :scroll-y="true" style="height: 700rpx; touch-action: none;">
						<view class="coupons-item" v-for="item in goodsCouponList" :key="item.id">
							<coupon-card mode='get' :name="item.name" :money="item.money" :condition="item.condition"
								:time="item.effective_time" :scene="item.use_scene" :coupon-id="item.id"
								:gotten="!!item.is_receive"
								:button="{ name: '领取', theme: 'primary', disable: !!item.is_available }"
								@button="getCoupon" />
						</view>
						<u-empty 
						  v-if="!goodsCouponList.length" 
						  text="暂无优惠券" 
						  src="/static/images/empty/coupon_icon.png" 
						  :icon-size="180"
						/>
					</scroll-view>
				</view>
			</view>
		</u-popup>
		<!-- E 优惠 -->


		<!-- S 规格 -->
		<view class="nr specification" @click="onGoodsOptions">
			<text class="muted">已选</text>
			<text class="m-l-20">{{ specValueStr }}</text>
			<u-icon name="arrow-right" class="muted" style="margin-left: auto;" />
		</view>

		<!-- 规格选择Popup -->
		<goods-spec 
		  v-model="showGoodsSpec" 
		  :defaultInfo="{
			  image: goodsInfo.image,
			  price: goodsInfo.sell_price,
			  stock: goodsInfo.total_stock
		  }"
		  :buttons="specButtonsList" 
		  :spec-list="goodsInfo.spec_value"
		  :spec-map="goodsInfo.spec_value_list"
		  @buy="handleBuy"
		  @cart="handleCartAdd" 
		  @change="changeGoodsSpec" 
		/>
		<!-- E 规格 -->


		<!-- diy -->
		<view v-for="(item, index) in pagesData" :key="index">
			
			<template v-if="item.name=='reviews'">
				<w-reviews v-if="item.show" :content="item.content" :styles="item.styles" :comment="goodsComment" :goods-id="goods_id" />
			</template>
			<template v-if="item.name=='goodsrecom'">
				<w-goodsrecom v-if="item.show" :content="item.content" :styles="item.styles" />
			</template>
		</view>


		<!-- 商品介绍 -->
		<view class="detail">
			<view class="detail-title nr">商品详情</view>
			<u-parse :html="goodsInfo.content" :show-with-animation="true"></u-parse>
		</view>


		<!-- 功能按钮组 -->
		<view class="functions">
			<view class="icon-group">
				<view class="icon-item" @tap="goService">
					<u-icon name="kefu-ermai" size="42" />
					<text>客服</text>
				</view>
				<view class="icon-item" @tap="changeCollect(isGoodsCollect)">
					<template v-if="isGoodsCollect">
						<u-icon name="star-fill" size="42" :color="themeColor" />
					</template>
					<template v-else>
						<u-icon name="star" size="42" />
					</template>
					<text>收藏</text>
				</view>
				<view class="icon-item" @tap="goCart">
					<u-icon name="shopping-cart" size="42" />
					<text>购物车</text>
				</view>
			</view>
			<view class="button-group">
				<view class="button-item button-item--cart" @click="onCart">加入购物车</view>
				<view class="button-item button-item--buy" @click="onBuy">立即购买</view>
			</view>
		</view>

		<share-popup 
		  v-model="showShare" 
		  :share-id="goods_id" 
		  pagePath="pages/goods_detail/goods_detail"
		  :config="{
			avatar: userInfo.avatar,
			nickname: userInfo.nickname,
			image: goodsInfo.poster || goodsInfo.image,
			price: goodsInfo.sell_price,
			marketPrice: goodsInfo.lineation_price,
			name: goodsInfo.name
		  }" 
		/>
		<!-- 页面状态 -->
		<page-status :status="pageStatus">
			<template #error>
				<u-empty :text="pageErrorMsg" src="/static/images/empty/shop.png" :icon-size="280"></u-empty>
			</template>
		</page-status>
		<float-tab />
	</view>
</template>

<script>
	import { apiGoodsDetail } from '@/api/goods'
	import { apiCartAdd, apiCouponGet } from '@/api/store'
	import { apiGoodsCollect, apiGoodsMarketing } from '@/api/goods'
	import { baseURL, basePath } from '@/config/app'
	import { apiGetPage } from '@/api/store'
	import { PageStatusEnum, OrderTypeEnum } from '@/utils/enum'
	import { mapGetters } from 'vuex'
	import { strToParams } from '@/utils/tools'
	
	export default {
		name: 'GoodsDetail',

		data() {
			return {
				// 页面状态
				pageStatus: PageStatusEnum['LOADING'],
				pagesData: [],
				pageErrorMsg: '',			// 页面异常信息
				
				showShare: false,
				goodsInfo: {}, 				// 商品信息
				goodsComment: {}, 			// 用户评价
				goods_id: '', 				// 商品ID

				isGoodsCollect: false, 		// 商品收藏

				showGoodsSpec: false, 		// 商品规格: 显示 | 隐藏
				showCoupons: false, 		// 领券：显示 | 隐藏

				goodsSpecOptions: {}, 		// 已选商品规格
				specButtonsList: [], 		// 规格按钮
				goodsCouponList: [], 		// 优惠券列表

				goodsCouponActive: '', 		// 使用的优惠券
				// 规格按钮组
				specButtonsGroups: {
					buy: {
						event: 'buy',
						text: '立即购买',
					},
					cart: {
						event: 'cart',
						text: '加入购物车',
					},
				},
			}
		},

		computed: {
			...mapGetters(['isLogin']),
			
			// 优惠券【视图】
			goodsCouponSpecs() {
				// 展示数量
				const COUNT = 2
				const coupons = this.goodsCouponList
				// 优惠券列表数量
				const Len = coupons.length
				// 承载容器
				const payload = []

				for (let i = 0;
					(i < COUNT) && (i <= Len - 1); ++i) {
					const value = coupons[i]['condition']
					payload.push(value)
				}

				return payload
			},
			
			// 已选商品规格
			specValueStr() {
				return this.goodsSpecOptions?.spec?.spec_value_str ?? ''
			},
		
		},

		methods: {
			// 获取装修页面
			getPage() {
				apiGetPage({
					type: 5,
					goods_id: this.goods_id
				}).then(data => {
					const { common, content } = data
					
					this.pagesData = content
					uni.setNavigationBarTitle({ title: common.title });
				})
			},
			// 更改规格
			changeGoodsSpec(options) {
				this.goodsSpecOptions = options
				console.log(options)
			},
			
			// 点击加入购物车按钮
			onCart() {
				this.showGoodsSpec = true
				this.specButtonsList = [this.specButtonsGroups.cart]
			},

			// 更改商品收藏状态
			changeCollect(value) {
				value = !!value ? 0 : 1
				if (!this.isLogin) return this.$Router.push('/pages/login/login')
				
				apiGoodsCollect({
					goods_id: this.goods_id,
					is_collect: value,
				}).then(data => {
					this.isGoodsCollect = value
					this.$toast({
						title: '操作成功'
					})
				}).catch(err => {
					console.log(err)
				})
			},

			// 去客服
			goService() {
				this.$Router.push({
					path: '/bundle/pages/service/service',
					query: {
						goods_id: this.goods_id,
						type: 'normal'
					}
				})
			},

			// 去购物车
			goCart() {
				this.$Router.replaceAll({
					path: '/pages/shop_cart/shop_cart'
				})
			},

			// 点击立即购买按钮
			onBuy() {
				this.showGoodsSpec = true
				this.specButtonsList = [this.specButtonsGroups.buy]
			},

			// 领取优惠券
			getCoupon(id) {
				if (!this.isLogin) return this.$Router.push('/pages/login/login')
				
				apiCouponGet({
						id
					})
					.then(() => {
						this.$toast({
							title: '领取成功'
						})
						this.initMarketing()
					})
					.catch(err => {
						console.log(err)
						// this.$toast({ title: '' })
					})
			},

			// 点击已选规格
			onGoodsOptions() {
				this.showGoodsSpec = true
				this.specButtonsList = [{
						...this.specButtonsGroups.cart,
						style: {
							border: `solid 1px ${this.themeColor}`,
							color: this.themeColor,
							backgroundColor: '#FFFFFF',
						}
					},
					this.specButtonsGroups.buy
				]
			},

			// 处理 加入购物车
			handleCartAdd({
				spec,
				number
			}) {
				if (!this.isLogin) return this.$Router.push('/pages/login/login')
				
				apiCartAdd({
					item_id: spec.id,
					goods_num: number
				}).then(() => {
					this.$toast({
						title: '已加入购物车'
					})
				}).catch(err => {
					throw new Error(err)
				})
			},

			// 处理 立即购买
			handleBuy({
				spec,
				number
			}) {
				this.$Router.push({
					path: '/pages/goods_order/goods_order',
					query: {
						from: OrderTypeEnum['GOODS'],
						payload: {
							source: 'buy_now',
							goods: [{
								goods_num: number,
								item_id: spec.id
							}]
						}
					}
				})
			},

			// 初始化商品详情数据
			initGoodsDetail() {
				return new Promise((resolve, reject) => {
					apiGoodsDetail({
						id: this.goods_id,
						visit: 1,
					}).then(data => {
						this.goodsInfo = data
						const hasComment = JSON.stringify(data.goods_comment) !== '[]'
						this.goodsComment = hasComment ? data.goods_comment : {}
						this.isGoodsCollect = !!data.is_collect
					}).then(data => {
						// #ifdef H5
						// 设置分享
						this.$store.dispatch('setWxShare', {
						    shareImage: data?.image,
						    shareDesc: data?.name
						})
						// #endif
						resolve(data)
					}).catch(err => {
						reject(err)
					})
				})
			},

			// 初始化优惠券
			initMarketing() {
				return new Promise((resolve, reject) => {
					apiGoodsMarketing({
						id: this.goods_id,
					}).then(data => {
						this.goodsCouponList = data.coupon
						resolve(data)
					}).catch(err => {
						reject(err)
					})
				})
			},
			
		},

		async onLoad() {
			const options = this.$Route.query

			// 商品ID赋值：点击 | 扫码
			options['scene'] 
				? this.goods_id = strToParams(options['scene'])['id']
				: this.goods_id = options.id
		
			try {
				if (!this.goods_id) throw new Error('该商品不存在')
				
				await this.getPage()
				// 商品详情数据
				await this.initGoodsDetail()
				// 促销
				await this.initMarketing()
				this.pageStatus = PageStatusEnum['NORMAL']
			} catch (err) {
				console.log(err)
				this.pageErrorMsg = err.message
				this.pageStatus = PageStatusEnum['ERROR']
			}
		},
		
		onShareAppMessage() {
			const { name, image } = this.goodsInfo
			return {
				title: name,
				path: `/pages/goods_detail/goods_detail?id=${this.goods_id}&invite_code=${this.userInfo.code}`,
				imageUrl: image
			}
		}
	}
</script>

<style lang="scss" scoped>
	.goods-detail {
		padding-bottom: calc(100rpx + 20rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(100rpx + 20rpx + env(safe-area-inset-bottom));
	}

	.goods-info {
		padding: 20rpx 24rpx;
		background-color: #FFFFFF;

		.share {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 134rpx;
			height: 60rpx;
			margin-right: -24rpx;
			border-radius: 30px 0 0 30px;
			background-color: #F6f6f6;
		}

		.goods-name {
			padding: 20rpx 0 10rpx 0;
			font-weight: 500;
		}
	}

	.discounts {
		display: flex;
		padding: 24rpx;
		margin-top: 20rpx;
		background-color: #FFFFFF;

		.coupon-tag {
			box-sizing: border-box;
			position: relative;
			display: flex;
			justify-content: center;
			min-width: 140rpx;
			height: 36rpx;
			padding: 0 20rpx;
			border-radius: 4px;
			margin-right: 10rpx;
			color: #FFFFFF;

			@include background_color() &::before,
			&::after {
				position: absolute;
				top: 50%;
				transform: translateY(-50%);
				display: block;
				content: '';
				width: 10rpx;
				height: 10rpx;
				border-radius: 50%;
				background-color: #FFFFFF;
			}

			&::before {
				right: -5rpx;
			}

			&::after {
				left: -5rpx;
			}
		}
	}

	.specification {
		display: flex;
		padding: 24rpx;
		margin-top: 20rpx;
		background-color: #FFFFFF;
	}

	.detail {
		padding: 24rpx;
		margin-top: 20rpx;
		background-color: #FFFFFF;

		&-title {
			text-align: center;
			font-weight: 500;
			padding-bottom: 24rpx;
		}
		::v-deep image {
			vertical-align: middle;
		}
		
		// #ifdef H5
		::v-deep img {
			vertical-align: middle;
		}
		
		// #endif
		// #ifdef MP-WEIXIN || APP-PLUS
		::v-deep ._img {
			display: block;
		}
		
		// #endif
	}

	.functions {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		height: calc(100rpx + constant(safe-area-inset-bottom));
		height: calc(100rpx + env(safe-area-inset-bottom));
		padding: 0 24rpx constant(safe-area-inset-bottom) 24rpx;
		padding: 0 24rpx env(safe-area-inset-bottom) 24rpx;
		border-top: $-solid-border;
		background-color: #FFFFFF;

		.icon-group {
			display: flex;
			justify-content: space-around;
			width: 268rpx;
			font-size: $-font-size-xxs;
			color: $-color-lighter;

			.icon-item {
				display: flex;
				flex-direction: column;
				align-items: center;
			}
		}

		.button-group {
			flex: 1;
			display: flex;
			justify-content: space-between;

			.button-item {
				flex: 1;
				box-sizing: border-box;
				display: flex;
				justify-content: center;
				align-items: center;
				height: 74rpx;
				margin-left: 14rpx;
				border-radius: 60px;

				&--cart {
					@include font_color();
					@include border_color();

					border-width: 1px;
					border-style: solid;
				}

				&--buy {
					@include background_color();
					color: #FFFFFF;
				}
			}
		}
	}

	.coupons {
		background-color: #f6f6f6;

		&-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 100rpx;
			padding: 0 30rpx;
			font-weight: 500;
			font-size: $-font-size-md;
			background-color: #FFFFFF;
		}

		&-main {
			padding: 20rpx;
			
			.coupons-item {
				&:nth-child(n+2) {
					margin-top: 20rpx;
				}
			}
		}
	}
</style>
